/**
 * 
 */
package adnotatio.rdf;

/**
 * Objects of this type used as "wrappers" for URLs and for anonymous unique
 * identifiers.
 * 
 * @author kotelnikov
 */
public class ID {

    /**
     * The counter used to generate unique "anonymous" identifiers
     */
    private static int fCounter;

    /**
     * The local name of this identifier
     */
    private final String fName;

    /**
     * The namespace of this identifier
     */
    private final String fNamespace;

    /**
     * The full URL corresponding to this ID
     */
    private String fURL;

    /**
     * This constructor generates a new unique "anonymous" identifier.
     */
    public ID() {
        this("id:", "" + fCounter++);
    }

    /**
     * Initializes internal fields (namespace and local name) by parsing the
     * given url.
     * 
     * @param url the url to set
     */
    public ID(String url) {
        int pos = url.lastIndexOf('#');
        if (pos < 0) {
            pos = url.lastIndexOf('/');
        }
        if (pos > 0) {
            fNamespace = url.substring(0, pos + 1);
            fName = url.substring(pos + 1);
        } else {
            fNamespace = url;
            fName = "";
        }
    }

    /**
     * Initializes internal fields with the given namespace and local name
     * 
     * @param namespace the namespace of this identifier
     * @param name the local name of this identifier
     */
    public ID(String namespace, String name) {
        fNamespace = namespace;
        fName = name;
    }

    /**
     * @see java.lang.Object#equals(java.lang.Object)
     */
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (!(obj instanceof ID))
            return false;
        ID id = (ID) obj;
        return getURL().equals(id.getURL());
    }

    /**
     * Returns the local name of this identifier
     * 
     * @return the local name of this identifier
     */
    public String getName() {
        return fName;
    }

    /**
     * Returns the namespace of this identifier
     * 
     * @return the namespace of this identifier
     */
    public String getNamespace() {
        return fNamespace;
    }

    /**
     * Returns the full URL corresponding to this id. This method returns the
     * result of concatenation of the namespace with the local name.
     * 
     * @return the URL corresponding to this id
     */
    public String getURL() {
        if (fURL == null) {
            fURL = fNamespace != null ? fNamespace + fName : fName;
        }
        return fURL;
    }

    /**
     * @see java.lang.Object#hashCode()
     */
    public int hashCode() {
        return getURL().hashCode();
    }

    /**
     * @see java.lang.Object#toString()
     */
    public String toString() {
        return getURL();
    }

}
